import os

from django.shortcuts import render
from django.conf import settings
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView


# Create your views here.
from orders.models import OrderInfo
from alipay import AliPay

from payment.models import Payment


class PaymentView(APIView):
    """支付宝的视图"""
    permission_classes = [IsAuthenticated]

    def get(self, request, order_id):
        """获取支付链接"""
        # 1. 判断订单信息是否正确
        try:
            order = OrderInfo.objects.get(pk=order_id,
                                          user=request.user,
                                          paymethod=OrderInfo.PAY_METHODS_ENUM['ALIPAY'],
                                          status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']
                                          )
        except OrderInfo.DoesNotExist:
            return Response({'message': '订单信息有误'}, status=status.HTTP_400_BAD_REQUEST)

        # 2.实例化支付宝的操作对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,   # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                'keys/alipay_publice_key.pem'),
            sign_type='RSA2',
            debug=settings.ALIPAY_DEBUG
        )
        # 3. 构造支付宝支付链接查询字符串
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),  # 订单金额
            subject='美多商城%s' % order_id,
            return_url=settings.ALIPAY_CALLBACK_URL + '/pay_success.html',
        )
        # 4. 拼接路径
        alipay_url = settings.ALIPAY_URL + '?' + order_string

        return Response({'alipay_url': alipay_url})


class PaymentStatusView(APIView):
    """订单状态保存的视图"""
    def put(self, request):
        data = request.query_params.dict()
        signature = data.pop('sign')

        # 获取支付宝对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )
        success = alipay.verify(data, signature)
        if success:
            # 订单编号
            order_id = data.get('out_trade_no')
            # 支付宝支付流水号
            trade_id = data.get('trade_no')
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )

            # 更新订单状态[一旦支付完成以后，就到待发货]
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM["UNSEND"])

            return Response({'trade_id': trade_id})

        else:
            return Response({'message': '无效请求'}, status=status.HTTP_403_FORBIDDEN)
